package com.kevin.Code.Tree;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;

/**
 * @author Vinlee Xiao
 * @Classname PopulatingNextRightPointersIneachnode
 * @Description Leetcode 116 填充每个节点的下一个右侧节点指针 注意细节
 * @Date 2022/1/2 10:23
 * @Version 1.0
 */


public class PopulatingNextRightPointersIneachnode {


    /**
     * 广度优先遍历
     *
     * @param root
     * @return
     */
    public RightNode connect(RightNode root) {
        //广度优先遍历
        Deque<RightNode> nodeDeque = new ArrayDeque<>();
        nodeDeque.addLast(root);

        while (!nodeDeque.isEmpty()) {

            int size = nodeDeque.size();

            for (int i = 0; i < size; i++) {
                RightNode node = nodeDeque.pollFirst();

                if (i < size - 1) {
                    node.next = nodeDeque.peekFirst();
                }

                if (node.left != null) {
                    nodeDeque.addLast(node.left);
                }

                if (node.right != null) {
                    nodeDeque.addLast(node.right);
                }
            }
        }

        return root;
    }
}
